using System.IO;

namespace BitTorrent.Client.Peer.Message.Standard {
    /// <summary>
    /// Message containing the pieces that have
    /// been successfully downloaded and verified via the hash.
    /// </summary>
    internal class Bitfield : PeerMessage
    {
        public Bitfield(BinaryReader reader, int length) {
            var buffer = new byte[length];
            reader.Read(buffer, 0, length);
            Field = new BitTorrent.Bitfield(buffer);
        }

        public BitTorrent.Bitfield Field { get; set; }

        public override byte[] GetMessage() {
            var message = new byte[4 + 1 + Field.Bytes.Length];

            using (var stream = new MemoryStream(message)) {
                var writer = new BinaryWriter(stream);
                writer.Write(ToBytes(Field.Bytes.Length + 1));
                writer.Write((byte) PeerMessageId.Bitfield);
                writer.Write(Field.Bytes);
            }

            return message;
        }
    }
}